<template>
  <MerakCollapse v-loading="queueLoading" v-model="collapseActive" curPageName="goods_merge_card">
    <MerakCollapseItem :title="$t('goods_allocation_merge.merge_attribute')" :name="CollapseName.prop">
      <template #handler>
        <template v-if="editor[CollapseName.prop]">
          <el-button @click="handleCancelEditForm">{{ $t("merak.cancel") }}</el-button>
          <el-button type="primary" @click="handleSaveEditForm">{{ $t("merak.save") }}</el-button>
        </template>
        <el-button
          v-else
          v-auth="{ authArr: auth, key: 'mergeCard' }"
          type="primary"
          :disabled="editor[CollapseName.enum]"
          :icon="Edit"
          link
          @click="handleEditForm"
        >
          {{ $t("merak.edit") }}
        </el-button>
      </template>
      <el-form
        ref="formRef"
        label-width="auto"
        :label-position="editor[CollapseName.prop] ? 'top' : 'right'"
        :model="formValue"
        :rules="formRules"
        :hide-required-asterisk="!editor[CollapseName.prop]"
      >
        <el-row :gutter="40">
          <el-col :span="span">
            <el-form-item prop="type_id" :label="$t('goods_attribute.type_id')">
              <el-select
                v-if="editor[CollapseName.prop]"
                v-model="formValue.type_id"
                class="qf_select"
                filterable
                @change="queryPropOptions"
              >
                <el-option v-for="option in options.type" :value="option.value" :label="option.label" />
              </el-select>
              <span v-else>{{ formValue.type_id_txt }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item
              prop="merge_prop_en"
              :label="$t('goods_allocation_merge.merge_prop_en')"
              :error="formError.merge_prop_en"
            >
              <el-input
                v-if="editor[CollapseName.prop]"
                v-model="formValue.merge_prop_en"
                v-trim
                class="qf_input"
                :maxlength="50"
              >
                <template #prefix>merge_</template>
              </el-input>
              <span v-else>merge_{{ formValue.merge_prop_en }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item
              prop="merge_prop_cn"
              :label="$t('goods_allocation_merge.merge_prop_cn')"
              :error="formError.merge_prop_cn"
            >
              <el-input
                v-if="editor[CollapseName.prop]"
                v-model="formValue.merge_prop_cn"
                v-trim
                class="qf_input"
                :maxlength="50"
              />
              <span v-else>{{ formValue.merge_prop_cn }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item
              prop="merge_prop_ru"
              :label="$t('goods_allocation_merge.merge_prop_ru')"
              :error="formError.merge_prop_rn"
            >
              <el-input
                v-if="editor[CollapseName.prop]"
                v-model="formValue.merge_prop_ru"
                v-trim
                class="qf_input"
                :maxlength="100"
              />
              <span v-else>{{ formValue.merge_prop_ru }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item prop="qifa_prop_id" :label="$t('goods_attribute.property_sale')">
              <el-select
                v-if="editor[CollapseName.prop]"
                v-model="formValue.qifa_prop_id"
                class="qf_select"
                filterable
                @change="handleSaleChange"
              >
                <el-option v-for="option in options.sales" :value="option.value" :label="option.label" />
              </el-select>
              <span v-else>{{ formValue.qifa_prop_id_txt }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item :label="$t('goods_allocation_merge.property_sale_id')">
              <span>{{ formValue.qifa_prop_id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item prop="cc_prop_id" :label="$t('goods_attribute.property_clearance')">
              <el-select
                v-if="editor[CollapseName.prop]"
                v-model="formValue.cc_prop_id"
                class="qf_select"
                :disabled="clearanceDisabled"
                filterable
                @change="handleClearanceChange"
              >
                <el-option v-for="option in clearanceOptions" :value="option.value" :label="option.label" />
              </el-select>
              <span v-else>{{ formValue.cc_prop_id_txt }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item :label="$t('goods_allocation_merge.cc_prop_id')">
              <span>{{ formValue.cc_prop_id }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </MerakCollapseItem>
    <MerakCollapseItem v-if="showEnumList" :name="CollapseName.enum">
      <template #title>
        <span>{{ $t("goods_allocation_merge.merge_attribute_value_list") }}</span>
        <span class="remark">&nbsp;&nbsp;&#40;{{ $t("goods_allocation_merge.have") }}</span>
        <span class="remark orange">&nbsp;{{ tableTotal }}&nbsp;</span>
        <span class="remark">{{ $t("goods_allocation_merge.records") }}&#41;</span>
      </template>
      <template #handler>
        <template v-if="editor[CollapseName.enum]">
          <el-button @click="handleCancelEditTable">{{ $t("merak.cancel") }}</el-button>
          <el-button type="primary" plain @click="handleAddEditTableRow">
            {{ $t("goods_allocation_merge.add_merge_enumeration_value") }}
          </el-button>
          <el-button type="primary" :disabled="MerakEditTableState.tableData.length === 0" @click="handleSaveEditTable">
            {{ $t("merak.save") }}
          </el-button>
        </template>
        <el-button
          v-else
          v-auth="{ authArr: auth, key: 'mergeCard' }"
          type="primary"
          :disabled="editor[CollapseName.prop]"
          :icon="Edit"
          link
          @click="handleEditTable"
        >
          {{ $t("merak.edit") }}
        </el-button>
      </template>
      <div :style="{ height: enumHeight }">
        <MerakEditTable
          ref="editTableRef"
          v-show="editor[CollapseName.enum]"
          v-bind="MerakEditTableState"
          style="height: 100%"
          @edit-form-fun="handleValidEditTable"
        >
          <template #qifa_propvalue_id="{ scope }">
            <el-select
              v-model="(scope as Record<string, any>).qifa_propvalue_id.value"
              filterable
              @change="value => handleSaleEnumChange(scope, value)"
            >
              <el-option v-for="option in renderSaleEnumOptions(scope.index)" :value="option.value" :label="option.label" />
            </el-select>
          </template>
          <template #cc_propvalue_id="{ scope }">
            <el-select
              v-model="(scope as Record<string, any>).cc_propvalue_id.value"
              filterable
              @change="
                value =>
                  ((scope as Record<string, any>).cc_propvalue_id.label = options.clearanceEnums.find(
                    option => option.value === value
                  )?.label)
              "
            >
              <el-option v-for="option in renderClearanceEnumOptions(scope.index)" :value="option.value" :label="option.label" />
            </el-select>
          </template>
          <template #handle="{ row }">
            <el-button type="danger" link @click="handleDeleteEditTableRow(row)">{{ $t("merak.delete") }}</el-button>
          </template>
        </MerakEditTable>
        <MerakXTable ref="xTableRef" v-show="!editor[CollapseName.enum]" v-bind="MerakXTableState" :query-data="queryData">
          <template #tools>
            <el-input
              v-model="searchValue"
              :placeholder="$t('goods_allocation_merge.search_enum')"
              style="width: 200px"
              :suffix-icon="Search"
              clearable
              @change="() => xTableRef?.reloadData()"
            />
          </template>
        </MerakXTable>
      </div>
    </MerakCollapseItem>
  </MerakCollapse>
</template>

<script setup lang="ts" name="mergePropertyCard">
import { getCurrentInstance, ref, reactive, computed, onMounted } from "vue";

import { useRoute } from "vue-router";

import { useGlobalStore } from "@/stores/modules/global";

import { FormRules, ElMessage, ElButton, ElForm, ElFormItem, ElRow, ElCol, ElInput, ElSelect, ElOption } from "element-plus";

import { Edit, Search } from "@element-plus/icons-vue";

import { MerakCollapse, MerakCollapseItem } from "@/components/MerakCollapse";

import MerakXTable, { MerakXTableInstance, MerakXTableProps } from "@/components/MerakXTable";

import MerakEditTable from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";

import useLoading from "@/hooks/useLoading";

import { ResultEnum } from "@/enums/httpEnum";
import {
  DataOptionType,
  initAttribute,
  getAttributeList,
  getAttribute,
  editMergeAttribute,
  editMergeAttributeValue
} from "@/api/modules/goodsArchive/mergeAttribute";
import { UserAuthType, getUserAuth } from "@/api/modules/user";

import { confirmWarningMsg } from "@/utils/messageUtils";

enum CollapseName {
  prop = "prop",
  enum = "enum"
}

type EditTableDataType = Record<
  string,
  {
    value?: string | number;
    label?: string;
    errTip?: string;
  }
>;

const currentInstance = getCurrentInstance();

const route = useRoute();

const { language } = useGlobalStore();

const { queueId, queueLoading, queueReset } = useLoading();

// 权限
const auth = ref<UserAuthType>();

// 表单 ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 超级表格 ref
const xTableRef = ref<MerakXTableInstance>();

// 编辑表格 ref
const editTableRef = ref<InstanceType<typeof MerakEditTable>>();

// 是否存在枚举值列表
const showEnumList = ref(false);

// 表格搜索
const searchValue = ref<string>("");

// 列表项统计
const tableTotal = ref(0);

// 折叠激活项
const collapseActive = reactive([CollapseName.prop, CollapseName.enum]);

// 编辑按钮
const editor = reactive({
  [CollapseName.prop]: false,
  [CollapseName.enum]: false
});

// copy 编辑参照
const copy = reactive<{
  formValue?: Record<string, any>;
  tableData?: EditTableDataType[];
  saleOptions?: DataOptionType[];
  clearanceOptions?: DataOptionType[];
}>({});

// 表单值
const formValue = reactive<Record<string, any>>({});

// 表单校验提示
const formError = reactive<Record<string, any>>({});

// 表单校验
const formRules = reactive<FormRules>({
  type_id: [{ required: true, message: currentInstance?.proxy?.$t("goods_allocation_merge.type_id_valid") }],
  merge_prop_en: [
    {
      required: true,
      trigger: "change",
      validator: (rule, value, callback) => {
        console.log(value, /^\s+/g.test(value));
        if (!value) {
          callback(new Error(currentInstance?.proxy?.$t("goods_allocation_merge.merge_prop_en_valid")));
        } else if (!/^[a-z][a-z0-9_]*$/.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("goods_allocation_merge.merge_prop_en_valid_limit")));
        } else {
          callback();
        }
      }
    }
  ],
  merge_prop_cn: [{ required: true, message: currentInstance?.proxy?.$t("goods_allocation_merge.merge_prop_cn_valid") }],
  merge_prop_ru: [{ required: true, message: currentInstance?.proxy?.$t("goods_allocation_merge.merge_prop_ru_valid") }],
  qifa_prop_id: [{ required: true, message: currentInstance?.proxy?.$t("goods_allocation_merge.qifa_prop_id_valid") }],
  cc_prop_id: [{ required: true, message: currentInstance?.proxy?.$t("goods_allocation_merge.cc_prop_id_valid") }]
});

// 表单依赖下拉项
const options = reactive<{
  // 商品类型
  type: DataOptionType[];
  // 销售属性
  sales: DataOptionType[];
  // 缓存清关属性
  cacheClearance: DataOptionType[];
  // 销售枚举值
  saleEnums: DataOptionType[];
  // 清关枚举值
  clearanceEnums: DataOptionType[];
}>({
  type: [],
  sales: [],
  cacheClearance: [],
  saleEnums: [],
  clearanceEnums: []
});

// 表格 props
const MerakXTableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  columns: [
    { field: "merge_propvalue_id", title: currentInstance?.proxy?.$t("goods_allocation_merge.merge_enum_id") },
    { field: "merge_propvalue_cn", title: currentInstance?.proxy?.$t("goods_allocation_merge.merge_propvalue_cn") },
    { field: "merge_propvalue_ru", title: currentInstance?.proxy?.$t("goods_allocation_merge.merge_propvalue_ru") },
    { field: "qifa_propvalue_id", title: currentInstance?.proxy?.$t("goods_allocation_merge.qifa_propvalue_id") },
    { field: "qifa_propvalue_id_txt", title: currentInstance?.proxy?.$t("goods_allocation_merge.qifa_propvalue_id_txt") },
    { field: "cc_propvalue_id", title: currentInstance?.proxy?.$t("goods_allocation_merge.cc_propvalue_id") },
    { field: "cc_propvalue_id_txt", title: currentInstance?.proxy?.$t("goods_allocation_merge.cc_propvalue_id_txt") },
    { field: "sort", title: currentInstance?.proxy?.$t("goods_attribute.sort") }
  ],
  toolbar: ["refresh"]
});

// 编辑表格行数据模板
const MerakEditTableRow = reactive<EditTableDataType>({
  merge_propvalue_id: {},
  merge_propvalue_cn: {},
  merge_propvalue_ru: {},
  qifa_propvalue_id: {},
  cc_propvalue_id: {},
  sort: {}
});

// 编辑表格 props
const MerakEditTableState = reactive<{
  headData: Array<Record<string, any>>;
  tableData: EditTableDataType[];
  headConfig: Record<string, any>;
}>({
  headData: [
    { field: "merge_propvalue_id", title: currentInstance?.proxy?.$t("goods_allocation_merge.merge_enum_id") },
    { field: "merge_propvalue_cn", title: currentInstance?.proxy?.$t("goods_allocation_merge.merge_propvalue_cn"), length: 50 },
    { field: "merge_propvalue_ru", title: currentInstance?.proxy?.$t("goods_allocation_merge.merge_propvalue_ru"), length: 100 },
    { field: "qifa_propvalue_id", title: currentInstance?.proxy?.$t("goods_allocation_merge.qifa_propvalue_id_txt") },
    { field: "cc_propvalue_id", title: currentInstance?.proxy?.$t("goods_allocation_merge.cc_propvalue_id_txt") },
    { field: "sort", title: currentInstance?.proxy?.$t("goods_attribute.sort") }
  ],
  tableData: [],
  headConfig: {
    merge_propvalue_cn: "input",
    merge_propvalue_ru: "input",
    qifa_propvalue_id: { isEdit: true },
    cc_propvalue_id: { isEdit: true },
    sort: "number"
  }
});

// 计算表单列数
const span = computed(() => (language === "zh" ? 6 : 8));

// 计算清关属性 disabled
const clearanceDisabled = computed(() => formValue.qifa_prop_id === undefined);

// 计算清关属性下拉选项
const clearanceOptions = computed(() => {
  const option = options.sales.find(option => option.value === formValue.qifa_prop_id);
  const sameTypeOptions = [...options.cacheClearance].filter(cacheOption => cacheOption.prop_type === option?.prop_type);
  return sameTypeOptions.some(cacheOption => cacheOption.label.includes(option?.label ?? ""))
    ? sameTypeOptions.filter(cacheOption => cacheOption.label.includes(option?.label ?? ""))
    : sameTypeOptions;
});

// 计算枚举值内容高度
const enumHeight = computed(() => {
  // 头部高度 + 标签高度 + 父级 padding
  const otherHegiht = 55 + 40 + 10 * 2;
  // 属性信息块高度
  const propHeight = language === "zh" ? (editor[CollapseName.prop] ? 233 : 172) : editor[CollapseName.prop] ? 314 : 222;
  // margin + 盒子 padding + 盒子 header + content padding
  const boxSize = 10 + 10 * 2 + 32 + 10 * 2;
  return `calc(100vh - ${otherHegiht}px - ${propHeight}px - ${boxSize}px)`;
});

// 计算企发销售属性值下拉过滤
const renderSaleEnumOptions = (index: number) => {
  const selectedKeys = MerakEditTableState.tableData
    .map((item, idx) => (index === idx ? undefined : item.qifa_propvalue_id.value))
    .filter(Boolean);
  return options.saleEnums.filter(option => !selectedKeys.includes(option.value));
};

// 计算清关属性值下拉过滤
const renderClearanceEnumOptions = (index: number) => {
  // const selectedKeys = MerakEditTableState.tableData
  //   .map((item, idx) => (index === idx ? undefined : item.cc_propvalue_id.value))
  //   .filter(Boolean);
  // return options.clearanceEnums.filter(option => !selectedKeys.includes(option.value));
  return options.clearanceEnums;
};

// 编辑表单
const handleEditForm = () => {
  copy.formValue = { ...formValue };
  copy.saleOptions = [...options.sales];
  copy.clearanceOptions = [...options.cacheClearance];
  editor[CollapseName.prop] = true;
};

// 取消编辑表单
const handleCancelEditForm = () => {
  formRef.value?.clearValidate();
  Object.keys(formValue).forEach(key => {
    formValue[key] = copy.formValue?.[key];
  });
  options.sales = [...(copy.saleOptions ?? [])];
  options.cacheClearance = [...(copy.clearanceOptions ?? [])];
  editor[CollapseName.prop] = false;
};

// 编辑列表
const handleEditTable = () => {
  copy.tableData = JSON.parse(JSON.stringify(MerakEditTableState.tableData));
  editor[CollapseName.enum] = true;
};

// 取消编辑列表
const handleCancelEditTable = () => {
  MerakEditTableState.tableData = [...(copy.tableData ?? [])];
  editor[CollapseName.enum] = false;
};

// 类型联动获取属性下拉
const queryPropOptions = (value: string | number) => {
  const option = options.type.find(option => option.value === value);
  formValue.type_id_txt = option?.label;
  formValue.qifa_prop_id = undefined;
  formValue.cc_prop_id = undefined;
  getAttribute({ type_id: value }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const { prop, cc_prop } = data;
      options.sales = [...(prop ?? [])];
      options.cacheClearance = [...(cc_prop ?? [])];
    }
  });
};

// 企发销售属性下拉变动
const handleSaleChange = (value: string | number) => {
  const option = options.sales.find(option => option.value === value);
  formValue.qifa_prop_id_txt = option?.label;
  formValue.cc_prop_id = undefined;
};

// 清关属性下拉变动
const handleClearanceChange = (value: string | number) => {
  const option = clearanceOptions.value.find(option => option.value === value);
  formValue.cc_prop_id_txt = option?.label;
};

// 添加编辑表格行
const handleAddEditTableRow = () => {
  MerakEditTableState.tableData.push(JSON.parse(JSON.stringify(MerakEditTableRow)));
};

// 删除编辑表格行
const handleDeleteEditTableRow = (row: any) => {
  if (typeof row?.index === "number") {
    MerakEditTableState.tableData.splice(row.index, 1);
  }
};

// 企发销售属性值下拉变动
const handleSaleEnumChange = (scope: any, value: string | number) => {
  const currentOption = options.saleEnums.find(option => option.value === value);
  const clearanceEnumOptions = renderClearanceEnumOptions(scope.index);
  const mateOption = clearanceEnumOptions.find(option => option.label.includes(currentOption?.label ?? ""));
  scope.qifa_propvalue_id.label = currentOption?.label;
  if (!!mateOption) {
    MerakEditTableState.tableData[scope.index].cc_propvalue_id.value = mateOption.value;
    MerakEditTableState.tableData[scope.index].cc_propvalue_id.label = mateOption.label;
  }
};

// 保存表单
const handleSaveEditForm = () => {
  Object.keys(formError).forEach(key => {
    formError[key] = undefined;
  });
  formRef.value?.validate().then(() => {
    confirmWarningMsg({
      msg: currentInstance?.proxy?.$t("goods_allocation_merge.edit_form_message") ?? "",
      callback: async (status: string) => {
        if (status === "confirm") {
          const prop: Record<string, any> = {};
          Object.keys(formValue).forEach(key => {
            if (!key.includes("_txt")) {
              prop[key] = formValue[key];
            }
          });
          queueReset();
          editMergeAttribute({ prop_id: route.query.propId, prop }, queueId.value).then(({ code, data, message }) => {
            if (code == ResultEnum.SUCCESS) {
              const option = options.sales.find(option => option.value === formValue.qifa_prop_id);
              if (option?.prop_type === 1) {
                if (
                  copy.formValue?.qifa_prop_id !== formValue.qifa_prop_id ||
                  copy.formValue?.cc_prop_id !== formValue.cc_prop_id
                ) {
                  // 属性已变更
                  searchValue.value = "";
                  xTableRef.value?.reloadTable();
                }
                showEnumList.value = true;
              } else {
                showEnumList.value = false;
              }
              editor[CollapseName.prop] = false;
              ElMessage.success(currentInstance?.proxy?.$t("goods_allocation_merge.edit_form_success"));
            } else {
              const msg = typeof message === "string" ? message : Object.values(message)?.[0];
              if (Array.isArray(data)) {
                data.forEach(key => {
                  formError[key] = msg;
                });
              } else {
                ElMessage.error(msg);
              }
            }
          });
        }
      }
    });
  });
};

const handleValidEditTable = (params: any) => {
  const excludeTableData = MerakEditTableState.tableData.filter((_, index) => index !== params?.index);
  if (excludeTableData.some(item => item?.merge_propvalue_cn?.value === params?.merge_propvalue_cn?.value)) {
    MerakEditTableState.tableData[params?.index].merge_propvalue_cn.errTip = currentInstance?.proxy?.$t(
      "goods_allocation_merge.merge_hint_three"
    );
  }
  if (excludeTableData.some(item => item?.merge_propvalue_ru?.value === params?.merge_propvalue_ru?.value)) {
    MerakEditTableState.tableData[params?.index].merge_propvalue_ru.errTip = currentInstance?.proxy?.$t(
      "goods_allocation_merge.merge_hint_two"
    );
  }
};

// 保存枚举值列表编辑
const handleSaveEditTable = () => {
  let flag = false;
  const errMap = {
    merge_propvalue_cn: currentInstance?.proxy?.$t("goods_allocation_merge.merge_propvalue_cn_valid"),
    merge_propvalue_ru: currentInstance?.proxy?.$t("goods_allocation_merge.merge_propvalue_ru_valid"),
    qifa_propvalue_id: currentInstance?.proxy?.$t("goods_allocation_merge.qifa_propvalue_id_valid"),
    cc_propvalue_id: currentInstance?.proxy?.$t("goods_allocation_merge.cc_propvalue_id_valid")
  };
  MerakEditTableState.tableData.forEach(data => {
    Object.keys(data).forEach(key => {
      if (key in errMap && !data[key].value && data[key].value !== 0) {
        flag = true;
        data[key].errTip = errMap[key];
      } else if (!!data[key].errTip) {
        flag = true;
      }
    });
  });
  if (flag) {
    ElMessage.error(currentInstance?.proxy?.$t("goods_allocation_merge.edit_table_error"));
    return;
  }
  confirmWarningMsg({
    msg: currentInstance?.proxy?.$t("goods_allocation_merge.edit_table_message") ?? "",
    callback: (status: string) => {
      if (status === "confirm") {
        const values = editTableRef.value?.submitData(false) as unknown;
        editMergeAttributeValue({
          prop_id: route.query.propId,
          propvalue: [...(values as Array<Record<string, any>>)].map(item => ({ ...item, sort: item.sort ?? 999 }))
        }).then(({ code, message }) => {
          if (code == ResultEnum.SUCCESS) {
            xTableRef.value?.reloadData();
            editor[CollapseName.enum] = false;
            ElMessage.success(currentInstance?.proxy?.$t("goods_allocation_merge.edit_table_success"));
          } else {
            const msg = typeof message === "string" ? message : Object.values(message)?.[0];
            ElMessage.error(msg);
          }
        });
      }
    }
  });
};

// 获取列表数据
const queryData: MerakXTableProps["queryData"] = async () => {
  return getAttributeList({ prop_id: route.query.propId }, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const { qifa_propvalue, cc_propvalue } = data.dataarr;
      const { propvalueList } = data.defaults;
      // 初始化下拉
      options.saleEnums = [...(qifa_propvalue ?? [])];
      options.clearanceEnums = [...(cc_propvalue ?? [])];
      // 编辑列表数据
      MerakEditTableState.tableData = [...(propvalueList ?? [])].map(item => {
        const payload: EditTableDataType = JSON.parse(JSON.stringify(MerakEditTableRow));
        Object.keys(MerakEditTableRow).forEach(key => {
          payload[key].value = item[key];
          payload[key].label = Object.keys(item).some(itemKey => itemKey.includes(key) && itemKey.includes("_txt"))
            ? item[`${key}_txt`]
            : item[key];
        });
        return payload;
      });
      // 数据统计
      tableTotal.value = propvalueList.length;
      return {
        list: propvalueList.filter(
          (item: Record<string, any>) =>
            item.merge_propvalue_cn.toLowerCase().includes(searchValue.value.toLowerCase()) ||
            item.merge_propvalue_ru.toLowerCase().includes(searchValue.value.toLowerCase())
        )
      };
    }
  });
};

// 初始化
onMounted(() => {
  getUserAuth("mergeStats", queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      auth.value = data;
    }
  });
  initAttribute({ prop_id: route.query.propId }, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const { type_id, qifa_prop_id, cc_prop_id } = data.dataarr;
      const { propvalueList, ...other } = data.defaults;
      const option = [...(qifa_prop_id ?? [])].find(option => option.value === other.qifa_prop_id);
      // 初始化下拉
      options.type = [...(type_id ?? [])];
      options.sales = [...(qifa_prop_id ?? [])];
      options.cacheClearance = [...(cc_prop_id ?? [])];
      // 表单回显
      Object.keys(other).forEach(key => {
        formValue[key] = other[key];
      });
      // 判断是否展示列表
      showEnumList.value = option?.prop_type === 1;
    }
  });
});
</script>

<style scoped lang="scss">
.el-button.is-link {
  min-width: auto;
}
.remark {
  color: #cfd3dc;
  font-size: 12px;
  &.orange {
    color: orange;
  }
}
:deep(.el-form-item__label-wrap) {
  margin-right: 30px;
}
</style>
